# -*- coding: utf-8 -*-
# @Function: 清空数据库
# @Description: 清空qa_knowledge表中的所有数据，提供安全的数据库清理功能
# @Usage: 直接运行此脚本清空数据库，或被其他模块导入使用
# @Dependencies: Z_config.py, Z_db_manager.py

import sys
import os
from D_db.core.db_manager import DBManager

class QADeleter:
    def __init__(self):
        """初始化删除器"""
        self.db_manager = DBManager()
    
    def delete_all_qa(self, confirm=False):
        """清空所有QA数据
        
        Args:
            confirm (bool): 是否确认删除，默认False需要用户确认
            
        Returns:
            bool: 删除是否成功
        """
        try:
            # 连接数据库
            self.db_manager.connect()
            
            # 如果没有确认，询问用户
            if not confirm:
                
                # 查询当前记录数
                count = self._get_record_count()
                if count == 0:
                    print("数据库中没有数据，无需清空。")
                    return True
                    
                print(f"当前数据库中共有 {count} 条QA记录")
            
            # 执行删除操作
            print("正在清空数据库...")
            deleted_count = self._execute_delete()

            return True
            
        except Exception as e:
            print(f"清空数据库失败: {e}")
            return False
        finally:
            # 关闭数据库连接
            self.db_manager.close()
    
    def _get_record_count(self):
        """获取当前记录数量
        
        Returns:
            int: 记录数量
        """
        count_sql = "SELECT COUNT(*) FROM qa_knowledge;"
        
        try:
            with self.db_manager.conn.cursor() as cursor:
                cursor.execute(count_sql)
                result = cursor.fetchone()
                return result[0] if result else 0
        except Exception as e:
            print(f"查询记录数量失败: {e}")
            return 0
    
    def _execute_delete(self):
        """执行删除操作
        
        Returns:
            int: 删除的记录数量
        """
        # 先获取要删除的记录数
        count = self._get_record_count()
        
        # 执行删除
        delete_sql = "DELETE FROM qa_knowledge;"
        
        try:
            with self.db_manager.conn.cursor() as cursor:
                cursor.execute(delete_sql)
                self.db_manager.conn.commit()
                return count
        except Exception as e:
            print(f"执行删除操作失败: {e}")
            self.db_manager.conn.rollback()
            raise
    
    def delete_by_category(self, category_id, confirm=False):
        """按类别删除QA数据
        
        Args:
            category_id (str): 要删除的类别ID
            confirm (bool): 是否确认删除
            
        Returns:
            bool: 删除是否成功
        """
        try:
            # 连接数据库
            self.db_manager.connect()
            
            # 查询该类别的记录数
            count_sql = "SELECT COUNT(*) FROM qa_knowledge WHERE category_id = %s;"
            
            with self.db_manager.conn.cursor() as cursor:
                cursor.execute(count_sql, (category_id,))
                count = cursor.fetchone()[0]
                
                if count == 0:
                    print(f"类别 '{category_id}' 中没有数据，无需删除。")
                    return True
                
                # 执行删除
                delete_sql = "DELETE FROM qa_knowledge WHERE category_id = %s;"
                cursor.execute(delete_sql, (category_id,))
                self.db_manager.conn.commit()
                
                print(f"成功删除类别 '{category_id}' 中的 {count} 条记录")
                return True
                
        except Exception as e:
            print(f"删除类别数据失败: {e}")
            self.db_manager.conn.rollback()
            return False
        finally:
            self.db_manager.close()

def main():
    """主函数"""
    
    deleter = QADeleter()
    deleter.delete_all_qa()

if __name__ == "__main__":
    main()